package com.sdi.columbus;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class TraceRoute extends MapActivity {
	
	
	
	
    MapView mapView;
    private static double lat;
	private static double lon;
    double[] vehiclelon;
    double[] vehiclelat;
    
    
    String add = "";
    String[] times;
    String[] speeds;
    String[] altitudes;
    String[] splitData,splitData1,splitPlace,splitdatepas;
	String subdate="",dats,dats1;
	String fdate,ldate,place;
	String ftime,fampm,ltime,lampm,subdate1="";
	String dateNTime,dateNTime1;
    private int latE6,flat,llat;
	private int lonE6,flon,llon;
	private MapController mapControl;
	private GeoPoint gp;
	private List<Overlay> mapOverlays;
	int size;
	GeoPoint first,last;
	String result,pathvalues,vehicleInfo;
	String TAG = "GPStest";
	// Set up the array of GeoPoints defining the route
	int numberRoutePoints;	
	GeoPoint routePoints [];   // Dimension will be set in class RouteLoader below
	              
	RouteSegmentOverlay route;   // This will hold the route segments
	boolean routeIsDisplayed = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
            Intent path=getIntent();
            Bundle bpath=path.getExtras();
           
            
            String pdates=bpath.getString("pdate");
//            int vehicleid=bpath.getInt("vid");
            String vehicleid=bpath.getString("vid");
            
            
            
            splitdatepas=pdates.split("-");
		
		
		    mapView=(MapView)findViewById(R.id.map);
		    mapView.setSatellite(false);
	        mapView.setTraffic(false);
	        mapView.setBuiltInZoomControls(true);   
	        int maxZoom = mapView.getMaxZoomLevel();
	        int initZoom = maxZoom-5;
	        mapControl = mapView.getController();
	        mapControl.setZoom(initZoom);
	        FetchPathValues fet=new FetchPathValues();
	        
	        
	        String startt=splitdatepas[1]+"-"+splitdatepas[0]+"-"+splitdatepas[2]+" "+"00:00";
	        String endt=splitdatepas[1]+"-"+splitdatepas[0]+"-"+splitdatepas[2]+" "+"11:59";
	        String accountId = getIntent().getStringExtra("accountID");
	           
	        try {
				result=fet.GetValues(accountId,vehicleid, startt, endt);
				JSONObject json = new JSONObject(result);
			    pathvalues= json.getString("GetGPSForIntervalResult");
				JSONObject json1 = new JSONObject(pathvalues);
			    vehicleInfo=json1.getString("GPSEntries");
			    
				
			    JSONArray jsonvehicle = new JSONArray(vehicleInfo);
			    size=jsonvehicle.length();
				System.out.println("you"+size);
				vehiclelon=new double[size];
				vehiclelat=new double[size];
				speeds=new String[size];
				times=new String[size];
				altitudes=new String[size];
				
				for (int i = 0; i < jsonvehicle.length(); i++)
				{
					 
		             JSONObject menuObject = jsonvehicle.getJSONObject(i);
		             
	                 vehiclelon[i]= Double.parseDouble(menuObject.getString("Longitude"));
	                 System.out.println("lati :"+vehiclelon[i]);
	                 
	                 vehiclelat[i]= Double.parseDouble(menuObject.getString("Latitude"));
	                 System.out.println("longi :"+vehiclelat[i]);
	                 
		             speeds[i]= menuObject.getString("Speed");
		             System.out.println("speed :"+speeds[i]);
		             
		             times[i]=menuObject.getString("TimeStamp");
		             System.out.println("time :"+times[i]);
		              
		             altitudes[i] = menuObject.getString("Altitude");
		             System.out.println("alt :"+altitudes[i]);
		             
		        }
		
				dateNTime=times[0];
				int p=dateNTime.indexOf("(");
	        	int q=dateNTime.indexOf("+");
	        	subdate=dateNTime.substring(p+1, q);
	            long dat=Long.parseLong(subdate);
	    		SimpleDateFormat formatter = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:ss a");
	    		Calendar calendar = Calendar.getInstance();
	    	    calendar.setTimeInMillis(dat);
	         	dats=formatter.format(calendar.getTime());
	    		splitData=dats.split(" ");
	            fdate=splitData[0];
	            ftime=splitData[1];
	            fampm=splitData[2];	
	            dateNTime1=times[size-1];
				int r=dateNTime1.indexOf("(");
	        	int s=dateNTime1.indexOf("+");
	        	subdate1=dateNTime1.substring(r+1, s);
	            long datt=Long.parseLong(subdate1);
	    		
	    	    calendar.setTimeInMillis(datt);
	         	dats1=formatter.format(calendar.getTime());
	    		splitData1=dats1.split(" ");
	            ldate=splitData1[0];
	            ltime=splitData1[1];
	            lampm=splitData1[2];	
	            
				
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
	     
	        
	        lat =vehiclelat[0];
			lon =vehiclelon[0];
			
			Log.d("vehiclelat", ""+lat);
			Log.d("vehiclelon", ""+lon);
	        // Convert lat/long in degrees into integers in microdegrees
	        latE6 =(int)(lat*1e6);
	        lonE6 =(int)(lon*1e6);
	        gp = new GeoPoint(latE6, lonE6);
	        mapControl.animateTo(gp);  
	    if(! routeIsDisplayed){
    		routeIsDisplayed = true;
    		loadRouteData();   				
    	} else {
    		if(route != null) route.setRouteView(false);
    		route = null; // To prevent multiple route instances if key toggled rapidly (see line 235)
    		routeIsDisplayed = false;
    		mapView.postInvalidate(); 
    	}
	    
	   
	   
	    		
	}
	public void loadRouteData(){
		
		int pointcounter;
		
		
		routePoints = new GeoPoint[size];
		for(pointcounter=0;pointcounter<size;pointcounter++)
		{
			latE6 =  (int) (vehiclelat[pointcounter]*1e6);
	        lonE6 = (int) (vehiclelon[pointcounter]*1e6);
    	//grade = Integer.parseInt(parser.getAttributeValue(null,"grade"));
    	   routePoints[pointcounter] = new GeoPoint(latE6, lonE6);
    	
    	
		}
		
		overlayRoute();
    }
	 public void overlayRoute() {
	    	if(route != null) return;  // To prevent multiple route instances if key toggled rapidly (see also line 116)
	    	// Set up the overlay controller
	    	route = new RouteSegmentOverlay(routePoints); // My class defining route overlay
	    	mapOverlays = mapView.getOverlays();
	    	mapOverlays.add(route);
	    	
	    	// Added symbols will be displayed when map is redrawn so force redraw now
	       // mapView.postInvalidate(); 
	    	flat =  (int) (vehiclelat[0]*1e6);
	        flon = (int) (vehiclelon[0]*1e6);
	        
	        llat= (int) (vehiclelat[size-1]*1e6);
	        llon= (int) (vehiclelon[size-1]*1e6);
	        
	        first=new GeoPoint(flat,flon);
	        last=new GeoPoint(llat,llon);
	        
	        
	        
	        try {
				ShowPlace(vehiclelat[0],vehiclelon[0]);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	           
	        
	    	Drawable drawable = this.getResources().getDrawable(R.drawable.marker);        
	        GmapItemizedOverlay itemizedoverlay = new GmapItemizedOverlay(drawable,this);        
	        
	        //String date = this.date.toString().replaceFirst("GMT", "");       

	        OverlayItem overlayitem = new OverlayItem(this.first,"First Location" ,"Place      :"+" "+splitPlace[0]+"\n"+"                "+splitPlace[2]+"\n"+"                "+splitPlace[3]+"\n"+"Date       :"+" "+ fdate+"\n"+"Time      :"+" "+ftime+fampm+"\n"+"Speed    :"+" "+speeds[0]+"\n"+"Altitude :"+" "+altitudes[0]);
	        try {
	        	
				ShowPlace(vehiclelat[size-1],vehiclelon[size-1]);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        OverlayItem overlayitems= new OverlayItem(this.last,"Last Location" ,"Place      :"+" "+splitPlace[0]+"\n"+"                "+splitPlace[2]+"\n"+"                "+splitPlace[3]+"\n"+"Date       :"+" "+ldate+"\n"+"Time      :"+" "+ltime+lampm+"\n"+"Speed    :"+" "+speeds[size-1]+"\n"+"Altitude :"+" "+altitudes[size-1]);
	        
	        itemizedoverlay.addOverlay(overlayitem);
	        itemizedoverlay.addOverlay(overlayitems);
	        
	        mapOverlays.add(itemizedoverlay);
	                
	        
	        
	    }
	 public static void putLatLong(double latitude, double longitude){
			lat = latitude;
			lon =longitude;
		}
		
		// This sets the s key on the phone to toggle between satellite and map view
		// and the t key to toggle between traffic and no traffic view (traffic view
		// relevant only in urban areas where it is reported).
		
		public boolean onKeyDown(int keyCode, KeyEvent e){
			if(keyCode == KeyEvent.KEYCODE_S){
				mapView.setSatellite(!mapView.isSatellite());
				return true;
			} else if(keyCode == KeyEvent.KEYCODE_T){
				mapView.setTraffic(!mapView.isTraffic());
				mapControl.animateTo(gp);  // To ensure change displays immediately
			}
			return(super.onKeyDown(keyCode, e));
		}
	 

	



	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	 public void ShowPlace( double la,double lo) throws JSONException, IOException
	    
	    {
	    	
	    	JSONObject user =  new JSONObject();
	    	user.put("latitude",String.valueOf(la));
	    	user.put("longitude",String.valueOf(lo));
	    	
	    	// Create a new HttpClient and Post Header
	    	
	    	HttpClient client = new DefaultHttpClient();
	    	URI website;
			try {
				website = new URI("http://deepam.cloudapp.net/ColumbusRESTService/ColumbusREST.svc/json/GetAddressForLatLong");
				HttpPost request = new HttpPost();
		    	request.setEntity(new StringEntity(user.toString()));
		    	request.addHeader("content-type", "application/json");      
		    	request.setURI(website);
		    	
		    	// Execute HTTP Post Request
		    	HttpResponse response = client.execute(request);
		    	HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity);
		    	System.out.println("frm show place"+response);
		    	System.out.println("Response in readable form"+result);
		    	
		    	
		    	JSONObject json = new JSONObject(result);
				String Status = json.getString("GetAddressForLatLongResult");
				
				JSONObject json1 = new JSONObject(Status);
				String Result=json1.getString("PlaceInfo");
				//code=Integer.parseInt(json1.getString("ErrorCode"));
				//UserInfo=json1.getString("UserInfo");
				
				
				
				JSONObject json2 = new JSONObject(Result);
		    	place=json2.getString("FullAddress");
		    	splitPlace=place.split(",");
		    	System.out.println("last output"+place);
		    	
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	  	    
	    	
	    }
		
	
}
